package cn.edu.zjicm.wordsnet_d.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import cn.edu.zjicm.wordsnet_d.R;
import cn.edu.zjicm.wordsnet_d.activity.base.WordBaseActivity;
import cn.edu.zjicm.wordsnet_d.datapersistent.AppPreference;
import cn.edu.zjicm.wordsnet_d.synchronize.UserInterface;
import cn.edu.zjicm.wordsnet_d.util.LogUtil;
import cn.edu.zjicm.wordsnet_d.util.StringUtil;

public class ChangeNickNameActivity extends WordBaseActivity implements OnClickListener {
	private EditText nickname;
	private ImageView clear;
	private Button commit;
	private String oldNickName;

	// private InputMethodManager imm;

	public static void startActivity(Context context) {
		Intent i = new Intent(context, ChangeNickNameActivity.class);
		context.startActivity(i);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTitleBarStyle(TITLE_BAR_STYLE_BACK_BUTTON);
		setTitleText("更改昵称");
		setContentView(R.layout.activity_change_nickname);

		// imm = (InputMethodManager)
		// getSystemService(Context.INPUT_METHOD_SERVICE);// 获得软键盘的对象
		// imm.showSoftInput(nickname, 0); // 显示键盘

		findViews();
		init();
	}

	private void findViews() {
		nickname = (EditText) findViewById(R.id.nick_name_edit);
		clear = (ImageView) findViewById(R.id.nick_name_clear);
		commit = (Button) findViewById(R.id.change_btn);
	}

	private void init() {
		nickname.addTextChangedListener(textWatcher);
		clear.setOnClickListener(this);
		commit.setOnClickListener(this);

		oldNickName = AppPreference.getNickName(ChangeNickNameActivity.this);
		if (oldNickName != null) {
			nickname.setText(oldNickName);
			nickname.setSelection(oldNickName.length());
		}
	}

	@Override
	public void onClick(View v) {
		if (v == commit) {
			changeNickName();
		} else if (v == clear) {
			nickname.setText("");
			clear.setVisibility(View.GONE);
			commit.setEnabled(false);
		}
	}

	TextWatcher textWatcher = new TextWatcher() {

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			// TODO Auto-generated method stub
			if (nickname.getText().length() > 0) {
				commit.setEnabled(true);
				clear.setVisibility(View.VISIBLE);
			} else {
				commit.setEnabled(false);
				clear.setVisibility(View.GONE);
			}
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {

		}

		@Override
		public void afterTextChanged(Editable s) {
			int editStart = nickname.getSelectionStart();
			int editEnd = nickname.getSelectionEnd();

			// 先去掉监听器，否则会出现栈溢出
			nickname.removeTextChangedListener(textWatcher);

			boolean toastHasShow = false;
			// 注意这里只能每次都对整个EditText的内容求长度，不能对删除的单个字符求长度
			while (StringUtil.calculateLength(s.toString()) > MAX_COUNT) { // 当输入字符个数超过限制的大小时，进行截断操作
				s.delete(editStart - 1, editEnd);
				editStart--;
				editEnd--;
				if (!toastHasShow) {
					Toast.makeText(ChangeNickNameActivity.this, "昵称不能超过16字", Toast.LENGTH_SHORT).show();
					toastHasShow = true;
				}
				LogUtil.e("length>32");
			}
			// mEditText.setText(s);将这行代码注释掉就不会出现后面所说的输入法在数字界面自动跳转回主界面的问题了，多谢@ainiyidiandian的提醒
			nickname.setSelection(editStart);

			// 恢复监听器
			nickname.addTextChangedListener(textWatcher);
		}

		final int MAX_COUNT = 32;
	};

	protected void changeNickName() {
		if (oldNickName.equals(nickname.getText().toString()))
			finish();
		else {
			String nickNameStr = nickname.getText().toString();
			// Pattern pattern = Pattern.compile("//w+");
			// Matcher matcher = pattern.matcher(nickNameStr);
			// Matcher m =
			// Pattern.compile("[\\w\\u4e00-\\u9fa5\\.]+").matcher(nickNameStr);//
			// 除了字母数字，下划线，点，汉字之外都非法
			// if (!m.matches()) {// 检查昵称中是否包含一些不合法符号
			if (nickNameStr.indexOf(":") != -1 || nickNameStr.indexOf(";") != -1) {
				Toast.makeText(ChangeNickNameActivity.this, "昵称不能包含有特殊字符", Toast.LENGTH_SHORT).show();
			} else {
				changeNickNameHandler.sendMessage(changeNickNameHandler.obtainMessage(UserInterface.MSG_START));
				UserInterface.getInstance(ChangeNickNameActivity.this).changeNickName(nickNameStr, changeNickNameHandler);
			}
		}
	}

	private Handler changeNickNameHandler = new Handler() {
		ProgressDialog dialog2 = null;

		public void handleMessage(android.os.Message msg) {
			if (msg.what != UserInterface.MSG_START)
				if (dialog2 != null) {
					dialog2.dismiss();
					dialog2 = null;
				}

			switch (msg.what) {
			case UserInterface.MSG_START:
				dialog2 = ProgressDialog.show(ChangeNickNameActivity.this, null, "正在更改昵称...");
				break;
			case UserInterface.MSG_SUCCESS:
				// Toast.makeText(LoginActivity.this, "登录成功",
				// Toast.LENGTH_SHORT).show();
				AppPreference.setNickName(ChangeNickNameActivity.this, nickname.getText().toString());
				finish();
				break;
			case UserInterface.MSG_UNSUCCESS:
				Toast.makeText(ChangeNickNameActivity.this, "昵称太抢手了，换一个", Toast.LENGTH_SHORT).show();
				break;
			case UserInterface.MSG_BAD_NETWORK:
				Toast.makeText(ChangeNickNameActivity.this, UserInterface.MSG_BAD_NETWORK_STRING, Toast.LENGTH_SHORT).show();
				break;
			case UserInterface.MSG_WEB_SITE_ACCESS_FAILURE:
				Toast.makeText(ChangeNickNameActivity.this, UserInterface.MSG_WEB_SITE_ACCESS_FAILURE_STRING, Toast.LENGTH_SHORT).show();
				break;
			default:
				break;
			}
		};
	};
}
